<template>
  <view :class="[`${prefixCls}-bind-mobile-container`]">
    <uv-form ref="uvForm" labelPosition="left" :model="formData" :rules="rules" :errorType="errorType">
      <uv-form-item prop="mobile" :customStyle="{ marginBottom: '4px' }">
        <uv-input
          v-model="formData.mobile"
          type="number"
          maxlength="11"
          :prefixIcon="$CDN('icons/phone.png')"
          :prefixIconStyle="{ width: '24px', height: '24px', marginRight: '8px' }"
          fontSize="14px"
          :customStyle="{ backgroundColor: '#fff', borderColor: '#fff !important' }"
          placeholder="请输入手机号"
        />
      </uv-form-item>

      <uv-form-item prop="captcha">
        <uv-input
          v-model="formData.captcha"
          type="number"
          maxlength="6"
          :prefixIcon="$CDN('icons/shield.png')"
          :prefixIconStyle="{ width: '24px', height: '24px', marginRight: '8px' }"
          fontSize="14px"
          :customStyle="{ backgroundColor: '#fff', borderColor: '#fff !important' }"
          placeholder="请输入验证码"
        >
          <template #suffix>
            <cu-verify-code mode="text" type="primary" :customStyle="{ fontSize: '14px' }" :mobile="formData.mobile" :extends="verifyExtends" />
          </template>
        </uv-input>
      </uv-form-item>
      <cu-agreements v-model="formData.agreement" scope="register" @change="getAgreement" />
      <uv-button
        type="primary"
        :customStyle="{ height: '44px', marginTop: '20px', fontSize: '16px' }"
        :loading="loginLoading"
        :disabled="loginLoading"
        :text="loginText"
        @click="onSubmit"
      />
    </uv-form>

    <!-- 绑定微信手机号 -->
    <!-- #ifdef MP-WEIXIN -->
    <view class="bind-operate" v-if="$Platform.name === 'WechatMiniProgram'">
      <uv-text type="primary" align="center" size="14" text="手机一键登录" openType="getPhoneNumber" @getphonenumber="getPhoneNumber" />
    </view>
    <!-- #endif -->
  </view>
</template>

<script>
import { AuthTypeEnum } from '@/common/enums/userEnum'
import FormValidate from '@/common/validate/form'

const rules = {
  mobile: FormValidate.mobile,
  captcha: FormValidate.smscode,
}
/**
 * props
 * @description
 * @property {Object} errorType 自定义样式
 * @property {String} errorType: message:输入框下方 | toast:弹出 | border-bottom: 作用域底部的下划线显示为红色 | none:不会进行任何提示
 */
import { mapActions } from 'vuex'

export default {
  name: 'cuBindMobile',
  mixins: [],
  props: {
    errorType: {
      type: [String],
      default: 'toast',
    },
  },
  data() {
    return {
      AuthTypeEnum,
      rules,
      formData: {
        mobile: '',
        captcha: '',
        agreement: false,
      },
      loginLoading: !1,
    }
  },
  // 侦听属性
  watch: {},
  // 计算属性
  computed: {
    loginText() {
      return this.loginLoading ? '登录中' : '登录'
    },

    verifyExtends() {
      return {}
    },
  },

  created() {},
  mounted() {},
  destroyed() {},
  options: {
    styleIsolation: 'shared',
  },
  methods: {
    ...mapActions('modal', ['SetAuthType']),
    ...mapActions('user', ['Login']),

    getAgreement(e) {
      this.formData.agreement = e
    },

    checkData() {
      let flag = !0
      const _formData = this.formData
      if (!_formData.agreement) {
        flag = !1
        this.$uv.toast('请阅读并勾选《用户协议》和《隐私政策》')
      }
      return flag
    },

    // 手机验证码登录
    onSubmit() {
      this.$refs.uvForm
        .validate()
        .then(async (res) => {
          const flag = res && this.checkData()
          if (flag) {
            this.loginLoading = !0
            // #ifdef MP
            // const { session_key } = await this.$Platform.useProvider().getSessionId()
            // #endif
            const _formData = {
              type: AuthTypeEnum.MOBILE.type,
              ...this.formData,
              // #ifdef MP
              // sessionKey: session_key,
              // #endif
            }
            await this.Login(_formData)
            this.loginLoading = !1
            this.$emit('onSuccess')
          }
        })
        .catch((errors) => {})
    },

    // 获取微信手机号 并 登录 后端接口还未实现
    async getPhoneNumber(e) {
      // console.log(e)
      if (e.errMsg === 'getPhoneNumber:ok') {
        const flag = this.checkData()
        if (flag) {
          // 先使用code换取session_key
          const { session_key } = await this.$Platform.useProvider().getSessionId()
          // 再使用session_key解密手机号
          const result = await this.$Platform.useProvider().bindUserPhoneNumber({ ...e, session_key })
          if (result?.mobile) {
            const _formData = {
              type: AuthTypeEnum.WXMOBILE.type,
              mobile: result.mobile,
              session_key,
            }
            // 最后使用微信解密的mobile手机号登录
            await this.Login(_formData)
            this.$emit('onSuccess')
          }
        }
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.#{prefixCls('bind-mobile-container')} {
  position: relative;
  ::v-deep .uv-form {
    .uv-form-item {
      .uv-input {
        .uv-input__content {
          height: 60rpx;
          line-height: 60rpx;
        }
      }
    }
  }

  .bind-operate {
    @include flex-bar;
    margin-top: 20rpx;
    .nvtext {
      font-size: 28rpx;
    }
    .primary {
      color: $uv-primary;
    }
  }
  .bind-operate {
    margin-top: 30rpx;
    .nvtext {
      font-size: 28rpx;
    }
    .primary {
      color: $uv-primary;
    }
    ::v-deep .uv-text__value {
      color: $uv-primary;
    }
  }
}
</style>
